package com.atguigu.gmall.pay.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.mq.config.RabbitService;
import com.atguigu.gmall.pay.service.PayService;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/pay")
public class PayController {

    @Autowired
    private PayService payService;
    @Autowired
    private RabbitService rabbitService;

    /**
     * 生成二维码地址
     * @param orderId
     * @return
     */
    @GetMapping(value = "/getPayUrl/{orderId}")
    public Result getPayUrl(@PathVariable(value = "orderId")Long orderId){
        Map<String, String> map = payService.createPayImg(orderId);
        return Result.ok(map);
    }

    /**
     * 查询支付结果
     * @param orderId
     * @return
     */
    @GetMapping(value = "/getPayResult/{orderId}")
    public Result getPayResult(@PathVariable(value = "orderId")Long orderId){
        Map<String, String> map = payService.getPayResult(orderId);
        return Result.ok(map);
    }

    /**
     * 微信的回调方法
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/callback/notify")
    public String wxNotify(HttpServletRequest request) throws Exception{
        //获取微信支付的结果
        ServletInputStream is = request.getInputStream();
        //输出流
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        //读取输入流
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1){
            os.write(buffer,0,len);
        }
        //将输出流转换为字符串
        String xmlString = new String(os.toByteArray(), "utf-8");
        //转换为map类型的数据
        Map<String, String> map = WXPayUtil.xmlToMap(xmlString);
        //发送一条消息
        rabbitService.sendMessage("pay_exchange","pay.order.result", JSONObject.toJSONString(map));
        //输出
        System.out.println(map);
        //通知微信收到了结果
        HashMap<String, String> result = new HashMap<>();
        result.put("return_code","SUCCESS");
        result.put("return_msg","OK");
        return WXPayUtil.mapToXml(result);
    }

    /**
     * 关闭交易
     * @param orderId
     * @return
     */
    @GetMapping(value = "/closePay/{orderId}")
    public Boolean closePay(@PathVariable(value = "orderId")Long orderId){
        return payService.closePay(orderId);
    }


}
